package com.example.myaku;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.myaku.IPutil.IPAdapter;
import com.example.myaku.network.SeaAKU;


import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private Button button;
    private TextView outputText;
    private SeaAKU seaAKU;
    private SwipeRefreshLayout swipeRefreshLayout;
    private boolean isScanning = false;
    private static boolean isScanningComplete = false;
    private RecyclerView ipRecyclerView;
    private IPAdapter ipAdapter;
    private static List<String> ipHistory = new ArrayList<>();


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        // 初始化视图组件
        button = view.findViewById(R.id.button);
        outputText = view.findViewById(R.id.outputText);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        ipRecyclerView = view.findViewById(R.id.ipRecyclerView);

        // 初始化 SeaAKU 单例
        seaAKU = SeaAKU.getInstance(requireContext());

        // 设置 RecyclerView
        ipRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        ipAdapter = new IPAdapter();
        ipRecyclerView.setAdapter(ipAdapter);

        Log.d("HomeFragment", "IP列表内容: " + ipHistory);
        Log.d("HomeFragment", "isScanningComplete: " + isScanningComplete);
        //if (ipHistory == null || ipHistory.isEmpty()) {
        if (!isScanningComplete) {
            seaAKU.startScan(requireContext());
//            seaAKU.startScanIfNotStarted(requireContext());
        } else {
            ipAdapter.updateIpList(ipHistory);
            outputText.setText("扫描完成!!!");
        }

        // 下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(this::onRefresh);

        // 设置发现设备监听器
        seaAKU.setOnDeviceFoundListener(ip -> {
            if (!ipHistory.contains(ip)) {
                ipHistory.add(ip);
                ipAdapter.updateIpList(ipHistory); // 刷新列表
            }
            //停止下拉刷新动画
            swipeRefreshLayout.setRefreshing(false);
        });
        // 扫描完成监听器
        seaAKU.setOnScanCompleteListener(() -> {
            isScanningComplete = true;
            outputText.setText("扫描完成!!!");
            Toast.makeText(requireContext(), "扫描完成!!!", Toast.LENGTH_SHORT).show();
        });


        // 设置点击事件
        ipAdapter.setOnIPClickListener(ip -> {
            String AKUurl = "http://" + ip;
//            Intent intent = new Intent(requireContext(), WebContentActivity.class);
//            intent.putExtra("AKUurl", AKUurl);
//            startActivity(intent);
            // 创建 Bundle 传递参数
            Bundle args = new Bundle();
            args.putString("AKUurl", AKUurl);

            // 创建目标 Fragment 并设置参数
            WebContentFragment fragment = new WebContentFragment();
            fragment.setArguments(args);

            // 获取 FragmentManager 并执行跳转
            requireActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, fragment) // 替换容器中的 Fragment
                    .addToBackStack(null) // 可选：添加到回退栈
                    .commit();
        });

        // 按钮点击：手动输入 IP 并跳转
        button.setOnClickListener(v -> showInputDialog());

        return view;
    }

    /**
     * 弹出输入框让用户手动输入 IP 地址
     */
    private void showInputDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("请输入IP地址");

        EditText input = new EditText(requireContext());
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        builder.setPositiveButton("确认", (dialog, which) -> {
            String userInput = input.getText().toString().trim();
            if (!userInput.isEmpty() && isValidIP(userInput)) {
                if (!ipHistory.contains(userInput)) {
                    ipHistory.add(userInput);
                    ipAdapter.updateIpList(ipHistory); // 刷新 RecyclerView
                }
                String AKUurl = "http://" + userInput;
                Intent intent = new Intent(requireContext(), WebContentFragment.class);
                intent.putExtra("AKUurl", AKUurl);
                startActivity(intent);
            } else {
                Toast.makeText(requireContext(), "请输入有效的IPV4地址", Toast.LENGTH_LONG).show();
            }
        });

        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }

    //    判断IPV4格式是否正确的方法
    private boolean isValidIP(String ip) {
        return ip.matches("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    }

    /**
     * 下拉刷新触发重新扫描
     */
    private void onRefresh() {
        if (isScanning) {
            swipeRefreshLayout.setRefreshing(false);
            return;
        }

        isScanning = true;
        new android.os.Handler(Looper.getMainLooper()).postDelayed(() -> {
            // 重启扫描
            seaAKU.startScan(requireContext());
            isScanning = false;
            swipeRefreshLayout.setRefreshing(false); // 停止刷新动画
        }, 800);
    }


    @Override
    public void onStop() {
        super.onStop();
        if (seaAKU != null) {
            seaAKU.stopScan(); // 停止扫描，避免内存泄漏
        }
    }
}
